#include "core/ClassObfuscator.h"
#include "core/WhitelistManager.h"
#include "utils/RandomGenerator.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>

ClassObfuscator::ClassObfuscator()
    : m_objcInterfaceRegex("@interface\\s+(\\w+)\\s*(?::\\s*\\w+)?")
    , m_objcImplementationRegex("@implementation\\s+(\\w+)")
    , m_swiftClassRegex("(?:class|struct|enum)\\s+(\\w+)")
{
}

ClassObfuscator::~ClassObfuscator() = default;

QMap<QString, QString> ClassObfuscator::generateMappings(const QStringList &files, WhitelistManager *whitelist)
{
    QMap<QString, QString> mappings;
    QStringList allClassNames;
    
    // 1. 收集所有类名
    for (const QString &filePath : files) {
        QStringList classNames = extractClassNames(filePath);
        allClassNames.append(classNames);
    }
    
    // 2. 去重
    allClassNames.removeDuplicates();
    
    // 3. 生成映射
    for (const QString &className : allClassNames) {
        if (shouldObfuscate(className, whitelist)) {
            QString obfuscatedName = generateObfuscatedName(className);
            
            // 确保没有冲突
            while (mappings.values().contains(obfuscatedName) || 
                   allClassNames.contains(obfuscatedName)) {
                obfuscatedName = generateObfuscatedName(className);
            }
            
            mappings[className] = obfuscatedName;
            qDebug() << "Mapping:" << className << "->" << obfuscatedName;
        }
    }
    
    return mappings;
}

QStringList ClassObfuscator::extractClassNames(const QString &filePath)
{
    QStringList classNames;
    
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return classNames;
    }
    
    QTextStream in(&file);
    QString content = in.readAll();
    file.close();
    
    // 检测文件类型
    bool isSwift = filePath.endsWith(".swift");
    
    if (isSwift) {
        // Swift类提取
        QRegularExpressionMatchIterator it = m_swiftClassRegex.globalMatch(content);
        while (it.hasNext()) {
            QRegularExpressionMatch match = it.next();
            classNames.append(match.captured(1));
        }
    } else {
        // Objective-C类提取
        // @interface
        QRegularExpressionMatchIterator it = m_objcInterfaceRegex.globalMatch(content);
        while (it.hasNext()) {
            QRegularExpressionMatch match = it.next();
            classNames.append(match.captured(1));
        }
        
        // @implementation
        it = m_objcImplementationRegex.globalMatch(content);
        while (it.hasNext()) {
            QRegularExpressionMatch match = it.next();
            QString className = match.captured(1);
            if (!classNames.contains(className)) {
                classNames.append(className);
            }
        }
    }
    
    return classNames;
}

QString ClassObfuscator::generateObfuscatedName(const QString &originalName)
{
    RandomGenerator generator;
    
    QString prefix = m_prefix.isEmpty() ? generator.generateString(3, true, false) : m_prefix;
    QString suffix = m_suffix.isEmpty() ? generator.generateString(3, true, false) : m_suffix;
    
    // 保留原始名称的一部分特征（可选）
    QString middle = originalName;
    if (middle.length() > 8) {
        middle = middle.left(4) + middle.right(4);
    }
    
    return prefix + middle + suffix;
}

bool ClassObfuscator::shouldObfuscate(const QString &className, WhitelistManager *whitelist)
{
    // 检查白名单
    if (whitelist && whitelist->isWhitelisted(className)) {
        return false;
    }
    
    // 检查系统类前缀
    QStringList systemPrefixes = {"NS", "UI", "CG", "CF", "CA", "AV", "MK", "CL", "CB"};
    for (const QString &prefix : systemPrefixes) {
        if (className.startsWith(prefix)) {
            return false;
        }
    }
    
    // 检查类名长度
    if (className.length() < 3) {
        return false;
    }
    
    return true;
}